import http from '@/libs/http'
import wx from 'weixin-js-sdk'
import store from '@/store'

/**
 * 坐标转换（将非高德坐标（GPS坐标、mapbar坐标、baidu坐标）转换成高德坐标），经度在前，纬度在后
 * https://lbs.amap.com/api/webservice/guide/api/convert
 * @param {经度,纬度} location 
 */
export function convertLocation(location) {
    return http({
        //经度在前，纬度在后
        url: 'http://restapi.amap.com/v3/assistant/coordinate/convert?locations='+location+'&coordsys=gps&key=2b7d6cf58cefb5511c218cf37d776ba0',
        method: 'get',
        withCredentials: false
    })
}

/**
 * 获取地址位置信息
 */
export function getLocation() {
    wx.ready(() => {
        wx.getLocation({
            type: "wgs84", 
            success: function(res) {
                var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                
                console.log("微信坐标：", "经度:" + longitude, "纬度:" + latitude);

                //将微信坐标转成高德坐标
                convertLocation(longitude + "," + latitude).then(response => {
                    console.log("微信坐标转换成高德坐标：" + response.data.locations);

                    const locations = response.data.locations

                    AMap.plugin('AMap.Geocoder',function(){//回调函数
                        //实例化Geocoder
                        var geocoder = new AMap.Geocoder();

                        //使用 geocoder 对象完成相关功能
                        geocoder.getAddress(locations, function (status, response) {
                            if(status === 'complete' && response.info === 'OK') {
                                console.log("地址信息：", response)

                                const result = response.regeocode.addressComponent
                                let location = {
                                    longitude: locations.split(",")[0],                 //经度
                                    latitude: locations.split(",")[1],	                //纬度
                                    province: result.province,                          //省
                                    city: result.city,		                            //市
                                    district: result.district,                          //区
                                    township: result.township,                          //街
                                    adcode: result.adcode,	                            //编码
                                    address: response.regeocode.formattedAddress	    //地址
                                }

                                //将获取到的位置信息存储到Vuex中
                                store.commit('SetLocation', location)
                            }
                        })
                    })
                })
            }
        });
    });
}